package com.appspot.yozmcup;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.yozmcup.DO.PMF;
import com.appspot.yozmcup.DO.Winner;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

@SuppressWarnings("serial")
public class SaveWinnerServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(SaveWinnerServlet.class.getName());
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
		
		String urlName = req.getParameter("url_name");
		String nickname = req.getParameter("nickname");
		String sexCode = req.getParameter("sex_code");
		String profileBigImgUrl = req.getParameter("profile_big_img_url");
		String introduce = req.getParameter("introduce");
		String date = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss").format(Calendar.getInstance(Locale.KOREA).getTime());
		
		DatastoreService dataStore = DatastoreServiceFactory.getDatastoreService();
		
		Query q = new Query("Winner");
		q.addFilter("urlName", Query.FilterOperator.EQUAL, urlName);
		PreparedQuery pq = dataStore.prepare(q);
		int dataCnt = pq.countEntities(FetchOptions.Builder.withLimit(1));
		
		if(dataCnt==0){
			Entity winner = new Entity("Winner"); 
			winner.setProperty("urlName", urlName);
			winner.setProperty("nickname", nickname);
			winner.setProperty("sexCode", sexCode);
			winner.setProperty("profileBigImgUrl", profileBigImgUrl);
			winner.setProperty("introduce", introduce);
			winner.setProperty("date", date);
			winner.setProperty("cnt", 1);
			
			dataStore.put(winner);
		}else{
			Key key = null;
			for(Entity result : pq.asIterable()){
				key = result.getKey();
				break;
			}
			if(key != null){
				PersistenceManager pm = PMF.get().getPersistenceManager();
				try {
					Winner winner = (Winner) pm.getObjectById(Winner.class, key);
					winner.setNickname(nickname);
					winner.setSexCode(sexCode);
					winner.setProfileBigImgUrl(profileBigImgUrl);
					winner.setIntroduce(introduce);
					winner.setDate(date);
					winner.setCnt(winner.getCnt()+1);
				} finally {
					pm.close();
				}
			}
		}

	}
}
